// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

// 获取云数据库用例
const db = cloud.database();
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  const obj = await db
    .collection('cart')
    .where({
      goods_id: event.id,
    })
    .get();
  if (obj.data.length > 0) {
    try {
      if (event.from === 'cart') {
        await db
          .collection('cart')
          .where({
            goods_id: event.id,
          })
          .update({
            data: {
              num: event.num,
            },
          });
      }
      if (event.from === 'details') {
        await db
          .collection('cart')
          .where({
            goods_id: event.id,
          })
          .update({
            data: {
              num: _.inc(1),
            },
          });
      }
      if (event.from === 'cartPay') {
        await db
          .collection('cart')
          .where({
            goods_id: event.id,
          })
          .update({
            data: {
              isBuyed: true,
            },
          });
      }
    } catch (e) {
      console.log(e);
    } finally {
    }
  } else {
    return await db.collection('cart').add({
      data: event.goods,
    });
  }
};
